package com.fuchuang.seckillsystem.service.impl;

import com.fuchuang.seckillsystem.dto.KeyConstants;
import com.fuchuang.seckillsystem.entity.Role;
import com.fuchuang.seckillsystem.entity.User;
import com.fuchuang.seckillsystem.exception.GlobalException;
import com.fuchuang.seckillsystem.mapper.RoleMapper;
import com.fuchuang.seckillsystem.mapper.UserMapper;
import com.fuchuang.seckillsystem.service.IRoleService;
import com.fuchuang.seckillsystem.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    
    @Resource
    private RoleMapper roleMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    @Override
    @Transactional
    public void grant(Integer userId, List<Integer> roleIds) {
        //参数校验
        if (userId == null || CollectionUtils.isEmpty(roleIds)) {
            throw new GlobalException(RespBeanEnum.PARAMS_ERROR);
        }
        User result = userMapper.selectByPrimaryKey(userId);
        if (result == null) {
            throw new GlobalException(RespBeanEnum.USER_NOT_EXIST_ERROR);
        }
        //删除用户拥有的角色
        roleMapper.deleteRoleIdByUserId(userId);
        //给用户分配角色
        Integer row = roleMapper.insertRoleIdAndUserId(userId, roleIds);
        if (row != roleIds.size()) {
            throw new GlobalException(RespBeanEnum.UPDATE_ERROR);
        }
        //删除redis中用户的登录数据
        redisTemplate.delete(KeyConstants.USER_DETAIL + result.getUsername());
    }
    
    @Override
    public List<Role> getUserRole(Integer userId) {
        if (userId == null) {
            throw new GlobalException(RespBeanEnum.PARAMS_ERROR);
        }
        List<Role> roles = roleMapper.queryRolesByUserId(userId);
        roles.forEach(role -> {
            role.setCreateTime(null);
            role.setUpdateTime(null);
            role.setIsValid(null);
        });
        return roles;
    }
    
    @Override
    public List<Role> getAllRole() {
        return roleMapper.queryAllRole();
    }
}
